#include "leetcode.h"

#include <unordered_map>

int longestConsecutive(std::vector<int>& nums) {
	std::unordered_map<int, int> record {};
	int max_len = 0;

	for (int n : nums) {
		auto it = record.find(n);
		if (it == record.end()) {
			record.insert(std::make_pair(n, 1));

			auto pre = record.find(n - 1);
			auto next = record.find(n + 1);
			int len = 1;
			if (pre != record.end() && next != record.end()) {
				len = pre->second + next->second + 1;
				record[n - pre->second] = len;
				record[n + next->second] = len;
			} else if (pre != record.end()) {
				len = 1 + pre->second;
				record[n] = len;
				record[n - pre->second] = len;
			} else if (next != record.end()) {
				len = 1 + next->second;
				record[n] = len;
				record[n + next->second] = len;
			}

			if (max_len < len) {
				max_len = len;
			}

			//cout << "n: " << n << "   len:" << len << "    max_len: " << max_len << endl;
		}
	}

	return max_len;
}
